package servlet;

import bean.CAF;
import bean.Page;
import dao.CAFDao;
import util.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 资讯反馈（后台）对应的servlrt
 *
 * @author dsf
 * @date|time 2017/9/17|15:58
 * @update:
 */
@WebServlet(name = "CAFM", urlPatterns = {"/cafm"})
public class CAFManageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String t = req.getParameter("t");
        if (t.equals("dlist")) {
            doDList(req, resp);
        }
        if (t.equals("detail")) {
            doDeatil(req, resp);
        }
        if (t.equals("search")) {
            doSearch(req, resp);
        }
        if (t.equals("reply")) {
            doReply(req, resp);
        }
        if (t.equals("delete"))
            doDelete(req, resp);
    }

    private void doDList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String page = "1";
        if (StringUtil.isNotEmpty(req.getParameter("page")))
            page = req.getParameter("page");
        int pageInt = Integer.parseInt(page);

        Connect con = Connect.getInstance();
        Page cafmPagePara = new Page();
        cafmPagePara.setSize(10);
        CAF cafDlistPara = new CAF();
        int pageSize = cafmPagePara.getSize();
        //查找所有处于未解决状态的条目
        cafDlistPara.setCafSolvedStatus("0");
        List<CAF> cafRes;
        try {
            //数据条数
            int cafResCount = CAFDao.cafCount(cafDlistPara, con);
            // 总分页数
            int pageNum = cafResCount % pageSize == 0 ? cafResCount / pageSize : cafResCount / pageSize + 1;
            if (pageInt > pageNum)// 最后一页数据被删除完后跳到第一页
                pageInt = 1;
            cafmPagePara.setStart((pageInt - 1) * cafmPagePara.getSize());
            System.out.println(cafmPagePara.getSize() + "页数" + pageNum);

            cafRes = CAFDao.search(cafDlistPara, cafmPagePara, con);
            req.setAttribute("cafRes", cafRes);
            req.setAttribute("pagenum", pageNum);// 总页数
            req.setAttribute("page", page);// 当前页
            System.out.println(page + "条数" + pageNum);
            req.getRequestDispatcher("/WEB-INF/cafmanage.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void doDeatil(HttpServletRequest req,
                          HttpServletResponse resp) throws ServletException, IOException {
        String cafId = req.getParameter("id");

        Connect con = JdbcUtils.getInstance();
        CAF cafDetailPara = new CAF();
        cafDetailPara.setCafId(cafId);
        List<CAF> cafRes;
        try {
            cafRes = CAFDao.search(cafDetailPara, null, con);
            System.out.println("文件：" + cafRes.get(0).getCafFile());
            req.setAttribute("cafRes", cafRes);
            req.getRequestDispatcher("/WEB-INF/cafreplay.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void doSearch(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String cafTitle = req.getParameter("title");
        String cafType = req.getParameter("type");
        String cafSolvedStatus = req.getParameter("status");

        String page = "1";
        if (StringUtil.isNotEmpty(req.getParameter("page")))
            page = req.getParameter("page");
        Page cafmPagePara = new Page();
        cafmPagePara.setSize(10);
        int pageSize = cafmPagePara.getSize();

        if (StringUtil.isNotEmpty(req.getParameter("page"))) {
            page = req.getParameter("page");
        }
        int pageInt = Integer.parseInt(page);

        if (StringUtil.isEmpty(cafTitle) && StringUtil.isEmpty(cafType) && StringUtil.isEmpty(cafSolvedStatus)) {
            req.setAttribute("page", "1");// 当前页置为1
            doDList(req, resp);//返回一览列表
        } else {

            Connect con = Connect.getInstance();
            CAF cafSearchPara = new CAF();

            cafSearchPara.setCafTitle(cafTitle);
            cafSearchPara.setCafType(cafType);
            cafSearchPara.setCafSolvedStatus(cafSolvedStatus);
            List<CAF> cafRes;
            try {
                //数据条数
                int cafResCount = CAFDao.cafCount(cafSearchPara, con);
                // 总分页数
                int pageNum = cafResCount % pageSize == 0 ? cafResCount / pageSize : cafResCount / pageSize + 1;
                if (pageInt > pageNum)// 最后一页数据被删除完后跳到第一页
                    pageInt = 1;
                cafmPagePara.setStart((pageInt - 1) * cafmPagePara.getSize());
                System.out.println(cafmPagePara.getSize());

                cafRes = CAFDao.search(cafSearchPara, cafmPagePara, con);
                req.setAttribute("pagenum", pageNum);// 总页数
                req.setAttribute("page", page);// 当前页
                System.out.println(page);
                req.setAttribute("cafRes", cafRes);
                req.setAttribute("title", cafTitle);
                req.setAttribute("type", cafType);
                req.getRequestDispatcher("/WEB-INF/cafmanage.jsp").forward(req, resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void doReply(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String cafId = req.getParameter("id");
        String cafSolvedStatus = req.getParameter("status");
        String cafReply = req.getParameter("content");
        if (StringUtil.isEmpty(cafReply)) {
            System.out.println("回复内容为不可空。");
            return;
        } else {
            Connect con = JdbcUtils.getInstance();
            CAF cafReplyPara = new CAF();
            cafReplyPara.setCafId(cafId);
            SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH/mm/ss");
            cafReplyPara.setCafReplyDate(df.format(new Date()));
            cafReplyPara.setCafSolvedStatus(cafSolvedStatus);
            cafReplyPara.setCafReply(cafReply);
            try {
                int replyRes = CAFDao.cafModify(cafReplyPara, con);
                if (replyRes != 0) {
                    System.out.println("回复成功！");
                    doDeatil(req, resp);
                } else System.out.println("回复失败！");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String cafId = req.getParameter("id");
        //得到要删除的文件名
        String fileName = req.getParameter("filename");
        if (StringUtil.isNotEmpty(cafId)) {
            if (StringUtil.isNotEmpty(fileName)) {
                fileName = new String(fileName.getBytes("iso8859-1"), "UTF-8");
                //上传的文件都是保存在/WEB-INF/upload目录下的子目录当中
                String fileSaveRootPath = this.getServletContext().getRealPath("/WEB-INF/upload");
                //通过文件名找出文件的所在目录
                String path = UploadSaveUtil.findFileSavePathByFileName(fileName, fileSaveRootPath);
                String fullFileName = path + "\\" + fileName;
                if (UploadSaveUtil.deleteFile(fullFileName)) {
                    System.out.println("删除附件成功！");
                } else System.out.println("删除附件失败！");
            }
            Connect con = JdbcUtils.getInstance();
            try {
                int delRes = CAFDao.cafDelete(cafId, con);
                if (delRes != 0) {
                    System.out.println("删除成功！");
                    req.getRequestDispatcher("/cafm?t=dlist").forward(req, resp);
                } else System.out.println("删除失败！");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
